package org.water.sys.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.config.AnnotationDrivenBeanDefinitionParser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.water.base.entity.ResultBaseBean;
import org.water.base.web.BaseController;
import org.water.common.bind.annotation.CurrentUser;
import org.water.common.bind.annotation.MethodDesc;
import org.water.common.bind.annotation.ResultFormat;
import org.water.common.param.AppSysParam;
import org.water.common.shiro.ShiroPwdHelper;
import org.water.common.util.RequestUtil;
import org.water.common.util.StringUtil;
import org.water.sys.entity.SysGroupRole;
import org.water.sys.entity.SysOnlineUser;
import org.water.sys.entity.SysRole;
import org.water.sys.entity.SysUser;
import org.water.sys.entity.SysUserRole;
import org.water.sys.service.RoleService;
import org.water.sys.service.UserRoleService;
import org.water.sys.service.UserService;
/**
 * 用户
 * @author qzy
 *
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

	
	public UserController() {
		// TODO Auto-generated constructor stub
	}
	@Autowired
	protected UserService userService;
	@Autowired
	protected RoleService roleService;
	@Autowired
	protected UserRoleService userRoleService;
	/**
	 * 初始用户密码
	 */
	protected String initUserPwd="123456";
	/**
	 * 根据用户名模糊查询
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/user_name")
	@ResultFormat
	public Page<SysUser> findByUserNameLike(Model model,HttpServletRequest request,
			HttpServletResponse response,@RequestParam("userName") String userName)
	{
		Page<SysUser> users=null;
		PageRequest pageRequest=new PageRequest(0, 20);
		users=userService.findByUserNameLike("%"+userName+"%",pageRequest);
		return users;
	}
	/**
	 * 根据用户名模糊查询
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/user_name2")
	@ResultFormat
	public List<SysUser> findByUserNameLike2(Model model,HttpServletRequest request,
			HttpServletResponse response,@RequestParam("userName") String userName)
	{
		List<SysUser> users=null;
		users=userService.findByUserNameLike("%"+userName+"%");
		return users;
	}
	/**
	 * 根据用户名模糊查询
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/user_name3")
	@ResultFormat
	public SysUser findByUserNameLike3(Model model,HttpServletRequest request,
			HttpServletResponse response,@RequestParam("userName") String userName)
	{
		SysUser users=null;
		users=userService.findUserByUserName(userName);   
		return users;
	}
	/**
	 * 更新别名
	 * @param model
	 * @return
	 */
	@RequestMapping("/update_alias")
	@ResultFormat
	public ResultBaseBean updateUserAliasName(Model model,HttpServletRequest request)
	{
		String id=request.getParameter("userId");
		String aliasName=request.getParameter("aliasName");
		Integer result=userService.updateUserAliasName(id, aliasName);
		return getBaseBean(true, "");
	}
	
	//用户管理
	/**
	 * 用户管理首页
	 * @return
	 */
	@RequestMapping("/index")
	public String index()
	{
		return "admin/user/userManager";
	}
	/**
	 * 修改用户密码
	 * @return
	 */
	@MethodDesc(name="用户管理",value="修改用户密码")
	@ResultFormat
	@RequestMapping("/update/pwd")
	public ResultBaseBean updateUserPwd(HttpServletRequest request,HttpServletResponse response)
	{
		ResultBaseBean bean=new ResultBaseBean();
		String oldPwd=request.getParameter("oldPwd");
		String newPwd=request.getParameter("newPwd");
		Subject subject=SecurityUtils.getSubject();
		SysUser user =(SysUser) subject.getPrincipal();
		String encodeOldPwd=ShiroPwdHelper.getEncodePWD(oldPwd, user.getUserName()+AppSysParam.USER_AES_KEY);
		if(!StringUtil.isEmpty(newPwd) && user!=null && user.pwdIsCorrect(encodeOldPwd))
		{
			String encodeNewPwd=ShiroPwdHelper.getEncodePWD(newPwd, user.getUserName()+AppSysParam.USER_AES_KEY);
			bean.setSuccess(true);
			user.setPassword(encodeNewPwd);
			userService.save(user);
		}
		else
		{
			bean.setSuccess(false);
			bean.setMsg("登录密错误");
		}
		return bean;
	}
	
	/**
	 * 初始用户密码
	 * @return
	 */
	@MethodDesc(name="用户管理",value="重置用户用户密码")
	@ResultFormat
	@RequestMapping("/reset/pwd")
	public ResultBaseBean initUserPwd(HttpServletRequest request,HttpServletResponse response)
	{
		ResultBaseBean bean=new ResultBaseBean();
		String userId=request.getParameter("userId");
		SysUser user=userService.findOne(userId);
		user.setPassword(ShiroPwdHelper.getEncodePWD(initUserPwd, user.getUserName()+AppSysParam.USER_AES_KEY));
		userService.save(user);
		bean.setSuccess(true);
		return bean;
	}
	/**
	 * 根据用户名模糊查询
	 * @param model
	 * @return
	 */
	@MethodDesc(name="用户管理",value="浏览用户")
	@RequestMapping(value="/qry")
	@ResultFormat
	public Page<SysUser> findByUserName(Model model,HttpServletRequest request,
			HttpServletResponse response,@RequestParam("userName") String userName,
			@RequestParam("pageIndex") int pageIndex,@RequestParam("pageSize") int pageSize)
	{
		Page<SysUser> users=null;
		PageRequest pageRequest=new PageRequest(pageIndex, pageSize);
		users=userService.findByUserNameLike("%"+userName+"%","%"+userName+"%",pageRequest);
		return users;
	}
	/**
	 * 保存用户
	 * @param request
	 * @param response
	 * @param sysUser
	 */
	@MethodDesc(name="用户管理",value="保存用户")
	@RequestMapping("/save")
	@ResultFormat
	public ResultBaseBean saveUser(HttpServletRequest request,HttpServletResponse response,@CurrentUser SysUser user)
	{
		SysUser sysUser=new SysUser();
		sysUser.setId(request.getParameter("id")!=""?request.getParameter("id"):null);
		sysUser.setUserName(request.getParameter("userName"));
		sysUser.setAliasName(request.getParameter("aliasName"));
		sysUser.setSex(Integer.parseInt(request.getParameter("sex")));
		sysUser.setPhone(request.getParameter("phone"));
		sysUser.setQq(RequestUtil.getParamNull(request, "qq"));
		sysUser.setEmail(RequestUtil.getParamNull(request, "email"));
		sysUser.setBirthDay(StringUtil.toDate(request.getParameter("birthDay"),"yyyy-MM-dd"));
		sysUser.setUsable(Integer.parseInt(request.getParameter("usable")));
		sysUser.setRemark(request.getParameter("remark"));
		sysUser.setDelStatus(0);
		if(StringUtils.isEmpty(sysUser.getId())) //新增时初始用户密码
		{
		    sysUser.setPassword(ShiroPwdHelper.getEncodePWD(initUserPwd, sysUser.getUserName()+AppSysParam.USER_AES_KEY));
		}
		else
		{
			sysUser.setPassword(user.getPassword());
		}
		sysUser.setCreateDate(new Date());
		sysUser.setCreateUser(user.getId());
		sysUser.setOrgCode(request.getParameter("orgCode"));
		
		ResultBaseBean bean= getBaseBean(true, "");
		Set sets=(Set) getValidator().validate(sysUser);//后台验证bean
		if(!sets.isEmpty())
		{
			bean.setSuccess(false);
			bean.setData(getErrorMsg(sets));
		}
		else
		{
			if(StringUtils.isEmpty(sysUser.getId()))
			{
				userService.save(sysUser);
			}
			else
			{
				userService.update(sysUser);
			}
		}
		return bean;
	}
	/**
	 * 删除用户  逻辑删除
	 * @param request
	 * @param response
	 * @param sysUser
	 */
	@MethodDesc(name="用户管理",value="删除用户")
	@RequestMapping("/del")
	@ResultFormat
	public ResultBaseBean delUser(HttpServletRequest request,HttpServletResponse response,SysUser sysUser)
	{
		sysUser=userService.findOne(sysUser.getId());
		sysUser.setDelStatus(1);
		userService.save(sysUser);
		return getBaseBean(true, "");
	}
	/**
	 * 查询单个用户
	 * @param request
	 * @param response
	 * @param sysUser
	 */
	@ResultFormat
	@RequestMapping("/one")
	public SysUser findOne(HttpServletRequest request,HttpServletResponse response,@RequestParam("userId") String userId)
	{
		return userService.findOne(userId);
	}
	/**
	 * 验证当前用户的密码是否正确
	 * @param pwd
	 * @param user
	 * @return
	 */
	@ResultFormat
	@RequestMapping("/checkPwd")
	public ResultBaseBean checkPwd(@RequestParam("pwd") String pwd,@CurrentUser SysUser user)
	{
		ResultBaseBean bean=new ResultBaseBean();
		String encodePwd=ShiroPwdHelper.getEncodePWD(initUserPwd, user.getUserName()+AppSysParam.USER_AES_KEY);
		if(user!=null && user.pwdIsCorrect(encodePwd))
		{
			bean.setSuccess(true);
		}
		else
		{
			bean.setSuccess(false);
		}
		return bean;
	}
	/**
	 * 验证当前用户的密码是否正确
	 * @param pwd
	 * @param user
	 * @return
	 */
	@ResultFormat
	@RequestMapping("/checkUserName")
	public ResultBaseBean checkUserName(@RequestParam("userName") String userName)
	{
		ResultBaseBean bean=new ResultBaseBean();
		SysUser user=userService.findUserByUserName(userName);
		if(user!=null)
		{
			bean.setSuccess(false);
		}
		else
		{
			bean.setSuccess(true);
		}
		return bean;
	}
	//在线用户
	/**
	 * 在线用户页面
	 * @param request
	 * @param response
	 * @return
	 */
	@MethodDesc(name="在线用户管理",value="浏览在线用户")
	@RequestMapping("/online/index")
	public String pageOnlineUser(HttpServletRequest request,HttpServletResponse response)
	{
		return "admin/user/onlineUser";
	}
	
	/**
	 * 获取在线用户
	 * @param request
	 * @param response
	 * @return
	 */
	@ResultFormat
	@RequestMapping("/online")
	public List<SysOnlineUser> findOnlineUser(HttpServletRequest request,HttpServletResponse response)
	{
		List<SysOnlineUser> users=userService.findOnlineUser();
		
		return users;
	}
	
	//用户关联角色
	/**
	 * 用户组关联的角色
	 * @param userId
	 * @return
	 */
	@RequestMapping("/role/all")
	public ResultBaseBean findGroupRoles(@RequestParam("userId") String userId)
	{
		ResultBaseBean bean=getBaseBean(true, "");
		HashMap<String, Object> data=new HashMap<>();
		ArrayList<String> selectRoles=new ArrayList<>();
		List<SysRole> roles=roleService.findAllRole();
		List<SysUserRole> grs=userRoleService.findByUserId(userId);
		if(grs!=null && !grs.isEmpty())
		{
			Iterator<SysUserRole> iterator=grs.iterator();
			while(iterator.hasNext())
			{
				SysUserRole ur=iterator.next();
				selectRoles.add(ur.getRoleId());
			}
		}
		data.put("roles", roles);
		data.put("selectRoles", selectRoles.toArray());
		bean.setData(data);
		return bean;
	}
	/**
	 * 保存用户关联角色
	 * @param groupRoles
	 */
	@CacheEvict(value={"userOwnResoucrce","userOwnResoucrceFun"},allEntries=true)
	@MethodDesc(name="用户管理",value="保存用户关联角色")
	@RequestMapping("/role/save")
	public ResultBaseBean saveUserGroupRoles(@RequestParam("userId") String userId,@RequestParam("roleIds") String roleIds)
	{
		ResultBaseBean bean=getBaseBean(true, "");
		List<SysUserRole> userRoles=new ArrayList<>();
		if(roleIds!=null || !"".equals(roleIds))
		{
			String[] roleIdArr=roleIds.split(",");
			for(String roleId:roleIdArr)
			{
				SysUserRole userRole=new SysUserRole();
				userRole.setUserId(userId);
				userRole.setRoleId(roleId);
				userRoles.add(userRole);
			}
			userRoleService.saveUserRoles(userId, userRoles);
		}
		else
		{
			bean.setSuccess(false);
			bean.setMsg("用户未关联角色，保存失败");
		}
		return bean;
	}
	
}
